package com.zjj.jvm2.memAllocation;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhanglei.zjj
 * @description 演示 finalize() 方法实现对象自救
 * @date 2023/3/14 22:45
 */
public class TestFinalize {
    public static final List<User> userList = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        User user = new User();
        System.out.println("user : " + user);

        // 模拟垃圾回收
        user = null;
        System.gc();

        Thread.sleep(1000);
        System.out.println("userList get(0) : " + userList.get(0));
    }
}

class User {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("User 实例进行垃圾回收了......");
        // 救活自己
        TestFinalize.userList.add(this);
    }
}
